const path = require("path");
const BaseHandler = require(path.join(__dirname, "../libs/baseHandler.js"));
const handler = new BaseHandler();
const Tags = require("../models/tag");
const Records = require("../models/record");
const Users = require("../models/users");
const _ = require("lodash");
const dayjs = require("dayjs");

handler.addRecord = async function (ctx) {
  const { amount, tag, user, detail, created } = ctx.request.body;

  const isTagExists = await Tags.exists({ _id: tag });
  if (!isTagExists) {
    throw new Error("该分类不存在!");
  }

  const isUserExists = await Users.exists({ _id: user });
  if (!isUserExists) {
    throw new Error("该用户不存在!");
  }

  let query = {
    amount,
    tag,
    user,
    created: dayjs(created).format("YYYY-MM-DD HH:mm:ss "),
  };

  if (detail) {
    query.detail = detail.replace(/\s/g, "");
  }

  const record = await Records(query).save();
  return handler.restSuccess(ctx, record);
};

handler.getRecordList = async function (ctx) {
  const { page = 1, pageSize = 7, created = -1 } = ctx.query;

  const condition = {};
  let { search = "{}" } = ctx.query;
  search = JSON.parse(search);
  const searchCondition = [];
  if (_.get(search, "amount")) {
    searchCondition.push({ amount: _.get(search, "amount") });
  }
  if (_.get(search, "tag")) {
    searchCondition.push({ tag: _.get(search, "tag") });
  }
  if (_.get(search, "user")) {
    searchCondition.push({ tag: _.get(search, "user") });
  }
  if (_.get(search, "detail")) {
    searchCondition.push({ tag: _.get(search, "detail") });
  }
  if (searchCondition.length > 0) {
    condition.$or = searchCondition;
  }

  const count = await Records.count(condition);
  const list = await Records.find(condition)
    .populate({
      path: `tag`,
      select: `name color isIncome`,
    })
    .populate({
      path: `user`,
      select: `username`,
    })
    .sort({ created })
    .skip((Number(page) - 1) * Number(pageSize))
    .limit(Number(pageSize))
    .lean();

  return handler.restSuccess(ctx, { list, count });
};

handler.editRecord = async function (ctx) {
  const { amount, tag, user, detail, id, created } = ctx.request.body;

  const isExists = await Records.exists({ _id: id });

  if (!isExists) {
    throw new Error("该记录不存在!");
  }

  let query = {
    detail: detail.replace(/\s/g, ""),
    amount,
    id,
    user,
    tag,
    created: dayjs(created).format("YYYY-MM-DD HH:mm:ss "),
  };

  const record = await Records.updateOne({ _id: id }, { $set: query });
  return handler.restSuccess(ctx, record);
};

handler.deleteRecord = async function (ctx) {
  let { ids } = ctx.request.body;
  // ids = JSON.parse(ids);
  if (_.isEmpty(ids)) {
    throw new Error("请选择要删除的记录！");
  }

  const result = await Records.deleteMany({ _id: { $in: ids } });
  handler.restSuccess(ctx, { result });
};

handler.getTagsAndUsers = async function (ctx) {
  const tags = await Tags.find({}, { name: 1 });
  const users = await Users.find({}, { username: 1 });
  handler.restSuccess(ctx, { tags, users });
};

module.exports = handler;
